package com.eeepay.eeepay_v2.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Filter;
import android.widget.Filterable;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.AgentInfo;
import com.eeepay.v2_library.adapter.ABBaseAdapter;
import com.eeepay.v2_library.adapter.ABViewHolder;
import com.eeepay.v2_library.log.LogUtils;

import java.util.ArrayList;
import java.util.List;

import cn.eeepay.api.grpc.nano.TerminalSerProto;

/**
 * Created by Ching on 2016/3/1.
 */
public class HistoryAdapter extends ABBaseAdapter<TerminalSerProto.AgentInfoMsg> implements Filterable{

    private List<TerminalSerProto.AgentInfoMsg> filterList;

    public HistoryAdapter(Context context) {
        super(context);
    }

    @Override
    public int getLayoutId() {
        return R.layout.agent_query_history_item;
    }

    @Override
    public void convert(ABViewHolder holder, TerminalSerProto.AgentInfoMsg model) {
        holder.setText(R.id.tv_query_history_item, model.agentName);
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();        // Holds the results of a filtering operation in values
                List<TerminalSerProto.AgentInfoMsg> tempList = new ArrayList<>();
                if (filterList == null) {
                    filterList = new ArrayList<>(list); // saves the original data in mOriginalValues
                }
                if(TextUtils.isEmpty(constraint)){
                    results.count = filterList.size();
                    results.values = filterList;
                }else{
                    constraint = constraint.toString().toLowerCase();
                    for (int i = 0; i < filterList.size(); i++){
                        if(filterList.get(i).agentName.contains(constraint)){
                            tempList.add(filterList.get(i));
                        }
                    }
                    results.count = tempList.size();
                    results.values = tempList;
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                list = (List<TerminalSerProto.AgentInfoMsg>) results.values;
                notifyDataSetChanged();

            }
        };
        return filter;
    }
}
